<template>
  <div class="statistics m-6">
    <el-row>
      <el-col class="mb-2">
        <el-checkbox
          v-model="checked"
          :true-label="1"
          :false-label="0"
          label="仅看有数据的法人"
          size="large"
        />
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="getTableData"
      style="width: 100%"
      :span-method="objectSpanMethod"
      :row-style="rowStyle"
    >
      <el-table-column prop="team" label="团队" width="80" />
      <el-table-column prop="pream1" label="下辖一级" width="80">
        <template #default="scope">
          {{ scope.row.pream1 || '/' }}
        </template>
      </el-table-column>
      <el-table-column prop="pream2" label="下辖二级" width="80">
        <template #default="scope">
          {{ scope.row.pream2 || '/' }}
        </template>
      </el-table-column>
      <el-table-column prop="today_revenue" label="当日收款金额(元)" width="150" />
      <el-table-column prop="month_revenue" label="当月收款金额(元)" width="150" />
      <el-table-column prop="year_revenue" label="当年收款金额(元)" width="150" />
      <el-table-column
        prop="months12_revenue"
        label="累计收款金额(万元) 连续12个月"
        width="150"
        align="center"
      />
      <el-table-column
        prop="months3_revenue"
        label="平均收款金额(元) 近3个月"
        width="140"
        align="center"
      />
      <el-table-column
        prop="target_date"
        label="预计突破预期 营业额时间"
        width="120"
        align="center"
      >
        <template #default="scope">
          {{ scope.row.target_date || '/' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-link
            type="primary"
            class="mr-1"
            :underline="false"
            @click="scope.row.team != '小计' && scope.row.team != '总计' && handleExpect(scope.row)"
          >
            {{
              scope.row.expected_revenue
                ? scope.row.expected_revenue
                : scope.row.team != '小计' && scope.row.team != '总计'
                ? '设置当年预期营业额'
                : ''
            }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="pream3" label="法人公司名称" width="220" />
    </el-table>
    <el-dialog
      class="codeStyle"
      v-model="isExpectedRevenue"
      :close-on-click-modal="false"
      title="设置当年预期营业额"
      width="430px"
      center
    >
      <el-form
        class="Grid Grid--justifyCenter"
        ref="ruleFormRef"
        style="max-width: 600px; padding: 10px 0"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        :size="formSize"
        status-icon
      >
        <el-form-item prop="expected_revenue">
          <el-input
            class="ya-select-field"
            type="number"
            style="width: 260px"
            min="0"
            placeholder="请输入预期营业额"
            v-model="expected_revenue"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="saveData()" type="primary">&nbsp;&nbsp;保存&nbsp;&nbsp;</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { summaryTeam, setExpectedRevenue } from '@/api/order/team'
import { useUserStoreHook } from '@/store/modules/user'

const userStore = useUserStoreHook()

export default {
  name: 'OrderTeam',
  components: {},
  data() {
    return {
      tableData: [],
      isExpectedRevenue: false,
      expected_revenue: '',
      cellData: {},
      loading: false,
      checked: 1
    }
  },
  computed: {
    getTableData() {
      let tableData = JSON.parse(JSON.stringify(this.tableData))
      let map = {}
      let arr = []
      if (this.checked) {
        arr = tableData.filter((item) => item.months3_revenue * 1 > 0)
        const countByKey = arr.reduce((acc, obj) => {
          const key = obj.team
          if (!acc[key]) {
            acc[key] = 0
          }
          acc[key]++
          return acc
        }, {})
        arr.forEach((item) => {
          if (!map[item.team] && countByKey.hasOwnProperty(item.team)) {
            map[item.team] = true
            item.childrenLength = countByKey[item.team]
          }
        })
        arr = this.getArr(arr)
      } else {
        arr = tableData
        arr = this.getArr(arr)
      }
      return arr
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    getArr(arr) {
      let _arr = this.groupBy(arr, 'team')
      let _total = {
        team: '总计',
        childrenLength: 1,
        colspan: 1,
        pream1: '',
        pream2: '',
        pream3: '',
        target_date: '',
        totalRowStyle: true
      }
      for (let key in _arr) {
        let _item = {
          team: '小计',
          childrenLength: 1,
          colspan: 1,
          pream1: '',
          pream2: '',
          pream3: '',
          target_date: '',
          rowStyle: true
        }
        for (let i = 0; i < _arr[key].length; i++) {
          _item['today_revenue'] = this.add(_item['today_revenue'] || 0, _arr[key][i].today_revenue)
          _item['month_revenue'] = this.add(_item['month_revenue'] || 0, _arr[key][i].month_revenue)
          _item['year_revenue'] = this.add(_item['year_revenue'] || 0, _arr[key][i].year_revenue)
          _item['months12_revenue'] = this.add(
            _item['months12_revenue'] || 0,
            _arr[key][i].months12_revenue
          )
          _item['months3_revenue'] = this.add(
            _item['months3_revenue'] || 0,
            _arr[key][i].months3_revenue
          )
        }
        _arr[key].push(_item)

        _total['today_revenue'] = this.add(_total['today_revenue'] || 0, _item.today_revenue)
        _total['month_revenue'] = this.add(_total['month_revenue'] || 0, _item.month_revenue)
        _total['year_revenue'] = this.add(_total['year_revenue'] || 0, _item.year_revenue)
        _total['months12_revenue'] = this.add(
          _total['months12_revenue'] || 0,
          _item.months12_revenue
        )
        _total['months3_revenue'] = this.add(_total['months3_revenue'] || 0, _item.months3_revenue)
      }
      console.log(_total)
      let _tableData = []
      for (let key in _arr) {
        _tableData = _tableData.concat(_arr[key])
      }
      _tableData = _tableData.concat(_total)
      return _tableData
    },
    groupBy(array, key) {
      return array.reduce((result, currentItem) => {
        // 使用 key 的值作为分组的键
        const groupKey = currentItem[key]

        // 如果 result 中不存在这个键，则创建一个数组
        if (!result[groupKey]) {
          result[groupKey] = []
        }

        // 将当前项推入对应的分组数组中
        result[groupKey].push(currentItem)

        return result
      }, {})
    },
    add(arg1, arg2) {
      var r1, r2, m, n
      try {
        r1 = arg1.toString().split('.')[1].length
      } catch (e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split('.')[1].length
      } catch (e) {
        r2 = 0
      }
      m = Math.pow(10, Math.max(r1, r2))
      n = r1 >= r2 ? r1 : r2
      return ((arg1 * m + arg2 * m) / m).toFixed(n)
    },
    // 查询
    search() {
      this.query.page = 1
      this.init()
    },
    init() {
      this.loading = true
      summaryTeam({}).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data
          this.loading = false
        }
      })
    },
    handleExpect(e) {
      this.cellData = e
      this.expected_revenue = e.expected_revenue
      this.isExpectedRevenue = true
    },
    objectSpanMethod(object) {
      if (object.columnIndex === 0) {
        console.log(object)
        if (object.row.childrenLength) {
          return {
            rowspan: object.row.childrenLength,
            colspan: object.row.colspan || 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    saveData() {
      setExpectedRevenue({
        team_id: this.cellData.team_id,
        expected_revenue: this.expected_revenue
      })
        .then((res) => {
          this.init()
          this.isExpectedRevenue = false
          ElMessage.success(res.msg)
        })
        .catch(() => {})
    },
    rowStyle(row, rowIndex) {
      if (row.row.rowStyle) {
        return 'background-color: #f5f7fa;'
      }
      if (row.row.totalRowStyle) {
        return 'background-color: #f5f7fa; font-weight: bold;'
      }
    }
  }
}
</script>
<style lang="scss" scoped></style>
